package com.youdianstar.app.ui.op

import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.os.Handler
import android.os.Looper
import android.view.MotionEvent
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import coil.load
import com.google.android.libraries.places.api.Places
import com.google.android.libraries.places.api.model.Place
import com.google.android.libraries.places.api.net.PlacesClient
import com.google.android.libraries.places.widget.Autocomplete
import com.google.android.libraries.places.widget.AutocompleteActivity
import com.google.android.libraries.places.widget.model.AutocompleteActivityMode
import com.google.common.base.Joiner
import com.gyf.immersionbar.ImmersionBar
import com.youdianstar.app.R
import com.youdianstar.app.BR
import com.youdianstar.app.adapter.ShopImgAdapter
import com.youdianstar.app.adapter.ShopTimeAdapter
import com.youdianstar.app.databinding.OpShopInfoBinding
import com.youdianstar.app.entity.*
import com.youdianstar.app.ui.MainActivity
import com.youdianstar.app.ui.account.PhoneCodeActivity
import com.youdianstar.app.util.AppDialogUtil
import com.youdianstar.app.util.DataAppManager
import com.youdianstar.app.util.DataHelperEx
import com.youdianstar.app.common.*
import com.youdianstar.app.common.base.BaseActivity
import com.youdianstar.app.common.entity.FileUpResult
import com.youdianstar.app.common.ex.setThrottleListener
import com.youdianstar.app.common.network.BaseApiResultObserver
import com.youdianstar.app.common.util.GsonUtil
import com.youdianstar.app.common.util.LanguageConfig
import com.youdianstar.app.common.util.LogUtil
import com.youdianstar.app.common.util.StrUtil
import com.youdianstar.app.common.ex.parseTx
import com.youdianstar.app.common.widget.SwitchButton
import com.youdianstar.app.common.auko.startActivity
import com.youdianstar.app.common.auko.startActivityForResult
import org.koin.androidx.viewmodel.ext.android.viewModel
import zion830.com.range_picker_dialog.OnTimeRangeSelectedListener
import zion830.com.range_picker_dialog.TimeRange
import zion830.com.range_picker_dialog.TimeRangePickerBottomSheet


/**
 * File: ShopInfoActivity
 * Author: 82149 Create: 2023/8/3 12:12
 * Changes (from 2023/8/3)
 * --------------------------------------------------
 * description:
 * ---------------------------------------------------
 *
 */
class ShopInfoActivity :BaseActivity<OpShopInfoBinding,OPMerchantViewModel>(){

    override fun layoutId(): Int = R.layout.op_shop_info

    override fun initVariableId(): Int = BR.viewModel

    override fun initViewModel(): OPMerchantViewModel {
        val model: OPMerchantViewModel by viewModel()
        return model
    }

    private var branchId = 0
    private val mHandler = Handler(Looper.myLooper()!!)
    //Google places 选择
    private var placesClient : PlacesClient?=null
    private val AUTOCOMPLETE_REQUEST_CODE = 1
    //当前多语言
    private var languageNow :String = ""
    //标识初始化数据
    private var isUIInit = false
    //是否访客身份
    private var isVisitor : Boolean = false
    //行业列表
    private val industryConfig = mutableListOf<OpIndustry>()
    //图片选择
    private var imageAdapter : ShopImgAdapter?=null
    private val IMAGE_REQUEST_CODE = 12
    private var selectType: Int = 0
    private var host :String =""
    //国家码+手机号
    private var countryCode: String? = null
    private val CODE_REQUEST_CODE = 0x18
    //营业时间
    private var isOpentimeEnable = false
    private val timeList = mutableListOf<OpenItem>()
    private var timeAdapter: ShopTimeAdapter? =null
    private var scrollIndex = 0 //标记 滚动位置

    private lateinit var requestBean : OpShopRequest

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        if (ev?.action == MotionEvent.ACTION_DOWN) {
            val view = currentFocus
            if (view != null && isShouldHideKeyBord(view, ev)) {
                this.hideSoftInput(view.windowToken)
                try {
                    mBinding.edtNameValue.clearFocus()
                    mBinding.edtAddressValue.clearFocus()
                    mBinding.edtPhoneValue.clearFocus()
                } catch (e:Exception){
                    e.printStackTrace()
                }
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    override fun initData() {
        super.initData()
        mBinding.headBar.initTitle(this,getString(R.string.shop_merchantDetail))
        mBinding.headBar.setRightText(getString(R.string.shop_save), R.color.color_39404D) {
            //保存
            saveShopInfo()
        }
        ImmersionBar.with(this).keyboardEnable(true).init()
        languageNow = LanguageConfig.instance.getLanguageCode()
        // Initialize the SDK
        Places.initialize(applicationContext, getString(R.string.google_places_key))
        // Create a new PlacesClient instance
        placesClient = Places.createClient(this)

        //图片列表
        imageAdapter = ShopImgAdapter(this, mutableListOf()) {
            if (isVisitor)
                return@ShopImgAdapter
            if (StrUtil.isEmpty(host))
                host = DataAppManager.instance.getConfig(ConfigKey.FILE_HOST)
            val url = DataAppManager.instance.imageList[it]
            val pathStr = if(url.contains("http")) url else host+url
            AppDialogUtil.instance.showImageCheckDialog(this, pathStr)
        }
        val manager = LinearLayoutManager(this)
        manager.orientation = LinearLayoutManager.HORIZONTAL
        mBinding.rcyPhotos.layoutManager = manager
        mBinding.rcyPhotos.adapter = imageAdapter

        //营业时间
        timeAdapter = ShopTimeAdapter(this,isFrozen = isVisitor , datas = mutableListOf(),object :ShopTimeAdapter.OnActionListener{
            override fun onItemPartSelect(position: Int, tvTime: TextView, item: OpenItem, index: Int) {
                showRangePicker(position,tvTime,item,index)
            }
        })
        mBinding.rcyList.layoutManager = LinearLayoutManager(this)
        mBinding.rcyList.adapter = timeAdapter

        branchId = intent.getIntExtra(Extra.IT_ID,0)
        //获取网点详情
        mViewModel.getShopDetails(branchId)
        isUIInit = true
    }

    override fun initLiveObserver() {
        super.initLiveObserver()
        mViewModel.shopDetailLiveData.observe(this, object : BaseApiResultObserver<OpShopInfo>() {
            override fun onDataResult(data: OpShopInfo?) {
                super.onDataResult(data)
                dismissDialog()
                data?.let {
                    setShopInfoLayout(it)
                }
            }

            override fun onNetError(code: Int, e: String?) {
                super.onNetError(code, e)
                dismissDialog()
                toastShow(e)
                if (code == 21334){
                    DataAppManager.instance.userUpdateTag = true
                    mHandler.postDelayed({
                        startActivity<MainActivity>()
                        finish()
                    },1000L)
                }
            }
        })

        mViewModel.editDetailLiveData.observe(this,object :BaseApiResultObserver<Any>(true){
            override fun onDataResult(data: Any?) {
                super.onDataResult(data)
                mHandler.postDelayed({
                    dismissDialog()
                    toastShow(getString(R.string.shop_saved))
                    DataAppManager.instance.shopEdtTag = branchId
                    finish()
                },1000L)
            }

            override fun onNetError(code: Int, e: String?) {
                super.onNetError(code, e)
                dismissDialog()
                toastShow(e)
            }
        })

        mViewModel.industriesLiveData.observe(this, object :BaseApiResultObserver<List<OpIndustry>>(){
            override fun onDataResult(data: List<OpIndustry>?) {
                super.onDataResult(data)
                dismissDialog()
                data?.let {
                    industryConfig.addAll(it)
                    showIndustriesDialog()
                }
            }

            override fun onNetError(code: Int, e: String?) {
                super.onNetError(code, e)
                dismissDialog()
                toastShow(e)
            }
        })

        mViewModel.fileUpLoadLiveData.observe(this, object : BaseApiResultObserver<FileUpResult>(false) {
            override fun onDataResult(data: FileUpResult?) {
                super.onDataResult(data)
                dismissDialog()
                data?.value?.let {
                    if (StrUtil.isEmpty(host))
                        host = DataAppManager.instance.getConfig(ConfigKey.FILE_HOST)
                    val iconUrl = if (it.contains("http")) it else host + it
                    mBinding.iconShop.load(iconUrl) {
                        error(R.mipmap.icon_default_logo)
                    }
                    requestBean.logo = it
                }
            }

            override fun onNetError(code: Int, e: String?) {
                super.onNetError(code, e)
                dismissDialog()
                toastShow(e)
            }
        })
    }

    override fun initClickEvent() {
        mBinding.clLogoContainer.setThrottleListener {
            showPhotoDialog()
        }

        mBinding.txShopPhotos.setThrottleListener {
            startActivityForResult<ShopImageActivity>(IMAGE_REQUEST_CODE)
        }

        mBinding.tvInCategory.setThrottleListener {
            if (industryConfig.isEmpty()){
                mViewModel.getShopIndustries()
            }else{
                showIndustriesDialog()
            }
        }

        mBinding.tvLocationValue.setThrottleListener {
            val fields = listOf(Place.Field.NAME, Place.Field.LAT_LNG, Place.Field.ADDRESS, Place.Field.ADDRESS_COMPONENTS)
            val intent = Autocomplete.IntentBuilder(AutocompleteActivityMode.FULLSCREEN, fields)
                .build(this)
            startActivityForResult(intent, AUTOCOMPLETE_REQUEST_CODE)
        }

        mBinding.tvPhoneCode.setThrottleListener {
            startActivityForResult<PhoneCodeActivity>(CODE_REQUEST_CODE)
        }

        mBinding.infoScroll.setOnScrollChangeListener { v, scrollX, scrollY, oldX, oldY ->
            scrollIndex = scrollY
        }
    }

    private fun setShopInfoLayout(info : OpShopInfo){
        requestBean = OpShopRequest(info.id)
        info.apply {
            requestBean.addressMap = addressMap
            requestBean.lat = lat
            requestBean.lng = lng
        }
        if (StrUtil.isEmpty(info.logo)) {
            mBinding.iconShop.setImageResource(R.mipmap.icon_default_logo)
        } else {
            if (StrUtil.isEmpty(host))
                host = DataAppManager.instance.getConfig(ConfigKey.FILE_HOST)
            info.logo?.let {
                val iconUrl = if (it.contains("http")) it else host + it
                mBinding.iconShop.load(iconUrl) {
                    error(R.mipmap.icon_default_logo)
                }
            }
        }
        DataAppManager.instance.imageList.clear()
        if (!StrUtil.isEmpty(info.images)){
            info.images?.let {
                val list = listOf<String>(*it.split(",".toRegex()).toTypedArray())
                DataAppManager.instance.imageList.addAll(list)
                imageAdapter?.refreshData(DataAppManager.instance.imageList)
            }
        }
        val isEmptyBanner = DataAppManager.instance.imageList.size ==0
        mBinding.tvChangeBanner.text = getString(if (isEmptyBanner) R.string.shop_add else R.string.shop_change)
        mBinding.rcyPhotos.visibility = if (isEmptyBanner) View.GONE else View.VISIBLE

        /*Base information*/
        mBinding.tvIdValue.text = info.branchCode?:"--"
        //0-待激活 1-正常 2-停止合作 3-待运营
        when(info.state){
            0->{
                mBinding.tvStatusValue.text = getString(R.string.shop_pendActvate)
                mBinding.tvStatusValue.setTextColor(Color.parseColor("#FF8F00"))
            }
            2->{
                mBinding.tvStatusValue.text = getString(R.string.shop_terminated)
                mBinding.tvStatusValue.setTextColor(Color.parseColor("#EB2300"))
            }
            3->{
                mBinding.tvStatusValue.text = getString(R.string.shop_pending)
                mBinding.tvStatusValue.setTextColor(Color.parseColor("#FF8F00"))
            }
            else ->{
                mBinding.tvStatusValue.text = getString(R.string.shop_inOperation)
                mBinding.tvStatusValue.setTextColor(Color.parseColor("#1EE592"))
            }
        }

        mViewModel.branchNameField.set(info.branchName?:"")
        //行业id
        if (info.industryName!=null){
            var industryTx = ""
            when(languageNow){
                Language.ES->{
                    industryTx = if (null!=info.description){
                        info.industryName.es.parseTx()+"("+info.description.es.parseTx()+")"
                    }else{
                        info.industryName.es.parseTx()
                    }
                }
                Language.ZH->{
                    industryTx = if (null!=info.description){
                        info.industryName.zh.parseTx()+"("+info.description.zh.parseTx()+")"
                    }else{
                        info.industryName.zh.parseTx()
                    }
                }
                else ->{
                    industryTx = if (null!=info.description){
                        info.industryName.en.parseTx()+"("+info.description.en.parseTx()+")"
                    }else{
                        info.industryName.en.parseTx()
                    }
                }
            }
            mBinding.tvInCategory.text = industryTx
        }else{
            mBinding.tvInCategory.text = "--"
        }
        //定位地址
        mBinding.tvLocationValue.text = if (StrUtil.isEmpty(info.addressMap)) "--" else info.addressMap
        mViewModel.branchAddressField.set(info.address?:"")
        //上级负责人/代理
        mBinding.tvUpperFranchisee.text = info.agentTx()
        //分成比例
        mBinding.tvSplitValue.text = info.ratio.toString()
        //计费规则
        mBinding.tvPricePlan.text = info.billingTitle?:"--"

        /*网点负责人信息*/
        mViewModel.contactNameField.set(info.principal?:"")
        //联系电话 --手机号
        if (info.code==null || info.code==0){
            countryCode = DataAppManager.instance.getPhoneCode()
        }else{
            countryCode = info.code.toString()
        }
        mBinding.tvPhoneCode.text = "+$countryCode"
        mViewModel.branchPhoneField.set(info.phone?:"")
        //店主账号
        mBinding.tvOwnerAccount.text = info.branchAccount?.accountTx()?:"--"

        /*设置营业时间*/
        timeList.clear()
        try {
            if (null!=info.openTime){
                val objJson = GsonUtil.jsonToBean(info.openTime, OpenTimeJson::class.java)
                isOpentimeEnable = objJson.check
                timeList.addAll(DataHelperEx.getOpentimeList(objJson))
            }else{
                timeList.addAll(DataHelperEx.getListDefault())
            }
        } catch (e :Exception){
            e.printStackTrace()
        }
        timeAdapter?.update(frozen = false,timeList)
        mBinding.swcOpenTime.isChecked = isOpentimeEnable
        setOpentimeLayout(isOpentimeEnable,false)

        mBinding.swcOpenTime.setOnCheckedChangeListener(object : SwitchButton.OnCheckedChangeListener{
            override fun onCheckedChanged(view: SwitchButton?, isChecked: Boolean) {
                if (!isUIInit){
                    isOpentimeEnable = isChecked
                    setOpentimeLayout(isChecked,true)
                }
            }
        })
        mHandler.postDelayed({
            //延时更新状态, 避免第一次设置数据引起滚动UI
            isUIInit = false
        },500L)
    }

    private fun setOpentimeLayout(isEnable : Boolean, scroll:Boolean){
        mBinding.viewLineOpen.visibility = if (isEnable) View.VISIBLE else View.GONE
        mBinding.rcyList.visibility = if (isEnable) View.VISIBLE else View.GONE
        if (scroll){
            if (scrollIndex ==0) scrollIndex = mBinding.clOpenTime.top+20
            mBinding.infoScroll.scrollTo(0,scrollIndex)
        }
    }

    private fun saveShopInfo(){
        //保存 Images
        if (DataAppManager.instance.imageList.size>0)
            requestBean.images = Joiner.on(",").join(DataAppManager.instance.imageList)
        else {
            requestBean.images = ""
        }

        //保存ShopName
        val nameValue :String = if (null!=mViewModel.branchNameField.get()) mViewModel.branchNameField.get()!! else ""
        if (StrUtil.isEmpty(nameValue)){
            toastShow(getString(R.string.shop_hintShopName))
            return
        }
        requestBean.branchName = nameValue
        //保存ShopAddress
        val addressValue :String = if (null!=mViewModel.branchAddressField.get()) mViewModel.branchAddressField.get()!! else ""
        if (StrUtil.isEmpty(addressValue)){
            toastShow(getString(R.string.shop_hintAddress))
            return
        }
        requestBean.address = addressValue
        //保存负责人名称
        val contactValue :String = if (null!=mViewModel.contactNameField.get()) mViewModel.contactNameField.get()!! else ""
        if (StrUtil.isEmpty(contactValue)){
            toastShow(getString(R.string.shop_hintInCharge))
            return
        }
        requestBean.principal = contactValue
        //联系方式--手机号
        val phoneNumTx = mBinding.edtPhoneValue.text.toString()
        if (StrUtil.isEmpty(phoneNumTx)){
            toastShow(getString(R.string.shop_hintContact))
            return
        }
        if (phoneNumTx.length <8){
            toastShow(getString(R.string.toast_validPhone))
            return
        }
        requestBean.code = countryCode?.toInt()
        requestBean.phone = phoneNumTx.trim()

        //保存营业时间
        val list = timeAdapter?.getOpentimeList()
        val openTimeJson = list?.let { OpenTimeJson(true, it) }
        openTimeJson?.check = isOpentimeEnable
        requestBean.openTime = GsonUtil.toJson(openTimeJson)

        mViewModel.saveShopDetailUpdate(requestBean)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == AUTOCOMPLETE_REQUEST_CODE){
            when (resultCode) {
                Activity.RESULT_OK -> {
                    data?.let {
                        val place = Autocomplete.getPlaceFromIntent(data)
                        LogUtil.i("TAG", "Place latLng: ${place.latLng?.latitude}, ${place.latLng?.longitude}")
                        LogUtil.i("TAG", "Place address: ${place.address}")
                        LogUtil.i("TAG", "Place Complete: ${place.addressComponents?.asList()}")
                        mBinding.tvLocationValue.text = place.address
                        //更新缓存
                        requestBean.lat = place.latLng?.latitude?:0.0
                        requestBean.lng = place.latLng?.longitude?:0.0
                        requestBean.addressMap = place.address
                    }
                }
                AutocompleteActivity.RESULT_ERROR -> {
                    data?.let {
                        val status = Autocomplete.getStatusFromIntent(data)
                        LogUtil.i("TAG", status.statusMessage ?: "")
                    }
                }
                Activity.RESULT_CANCELED -> {}
            }
            return
        }
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == IMAGE_REQUEST_CODE && resultCode== Activity.RESULT_OK){
            imageAdapter?.refreshData(DataAppManager.instance.imageList)
            mBinding.tvChangeBanner.text = getString(if (DataAppManager.instance.imageList.size == 0) R.string.shop_add else R.string.shop_change)
            mBinding.rcyPhotos.visibility = if (DataAppManager.instance.imageList.size>0) View.VISIBLE else View.GONE
        }else if (requestCode == CODE_REQUEST_CODE && resultCode == Activity.RESULT_OK){
            //选择国家/地区码
            countryCode = data?.getStringExtra(Extra.IT_CODE)
            mBinding.tvPhoneCode.text = "+$countryCode"
        }
    }

    /**行业选择弹框*/
    private fun showIndustriesDialog(){
        AppDialogUtil.instance.showIndustrySelectSheet(this,industryConfig, selectAction = { index->
            industryConfig[index].let { config->
                requestBean.industryId = config.id
                var industryTx = ""
                when(languageNow){
                    Language.ES->{
                        industryTx = if (null!=config.description){
                            config.industryName?.es.parseTx()+"("+config.description.es.parseTx()+")"
                        }else{
                            config.industryName?.es.parseTx()
                        }
                    }
                    Language.ZH->{
                        industryTx = if (null!=config.description){
                            config.industryName?.zh.parseTx()+"("+config.description.zh.parseTx()+")"
                        }else{
                            config.industryName?.zh.parseTx()
                        }
                    }
                    else ->{
                        industryTx = if (null!=config.description){
                            config.industryName?.en.parseTx()+"("+config.description.en.parseTx()+")"
                        }else{
                            config.industryName?.en.parseTx()
                        }
                    }
                }
                mBinding.tvInCategory.text = industryTx
            }
        })
    }

    /**时间区间选择*/
    private fun showRangePicker(position: Int, tvTime: TextView, item: OpenItem, index: Int){
        LogUtil.e("-----IndexRange:"+item.getIndexRange(index))
        TimeRangePickerBottomSheet.Builder()
            .setTimeRange(item.getIndexRange(index))
            .setOnTimeRangeSelectedListener(object : OnTimeRangeSelectedListener {
                override fun onTimeSelected(timeRange: TimeRange) {
                    tvTime.text = timeRange.numberTimeRange
                    when(index){
                        0->{
                            item.addPartItem(0,timeRange)
                            item.rangeTime1 = DataHelperEx.getRangeList(timeRange)
                        }
                        1->{
                            item.addPartItem(1,timeRange)
                            item.rangeTime2 = DataHelperEx.getRangeList(timeRange)
                        }
                        2->{
                            item.addPartItem(2,timeRange)
                            item.rangeTime3 = DataHelperEx.getRangeList(timeRange)
                        }
                        3->{
                            item.addPartItem(3,timeRange)
                            item.rangeTime4 = DataHelperEx.getRangeList(timeRange)
                        }
                    }
                    timeAdapter?.notifyItemChanged(position)
                }
            })
            .build()
            .show(this)
    }


    /****************************图片选择部分*******************************/

    /**
     * 图片选择器
     */
    private fun showPhotoDialog() {
        AppDialogUtil.instance.showSelectDialog(this) { selectIndex ->
            selectType = selectIndex
            when (selectIndex) {
                PHOTO_CAMERA -> requestCameraPermission {
                    showPhotoPicker(PHOTO_CAMERA)
                }
                PHOTO_ALBUM -> requestAlbumPermission {
                    showPhotoPicker(PHOTO_ALBUM)
                }
            }
        }
    }

    /**
     * 调用-ImagePicker
     * @param type
     */
    private fun showPhotoPicker(type: Int) {
        startSLImagePicker(this, type = type, needCrop = true) { path ->
            mViewModel.upLoadImage(path)
        }
    }

    override fun onPermissionsGranted(requestCode: Int, perms: List<String>) {
        super.onPermissionsGranted(requestCode, perms)
        if (requestCode == REQUEST_PERMISSION_CODE)
            showPhotoPicker(selectType)
    }

    override fun onDestroy() {
        mHandler.removeCallbacksAndMessages(null)
        super.onDestroy()
    }
}